package com.jzo2o.orders.manager.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.mapper.OrdersRefundMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrdersHandler {
    @Autowired
    private IOrdersManagerService ordersManagerService;
    @Autowired
    private RefundRecordApi refundRecordApi;
    @Autowired
    private OrdersRefundMapper ordersRefundMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersHandler ordersHandler;

    /**
     * 支付超时取消订单
     * 每分钟执行一次
     */
    @XxlJob("cancelOverTimePayOrder")
    public void cancelOverTimePayOrder() {
        //1、根据订单创建时间查询超过15分钟未支付的订单
        List<Orders> orders = ordersManagerService.lambdaQuery()
                .eq(Orders::getOrdersStatus, OrderStatusEnum.NO_PAY.getStatus())//查询待支付状态的订单
                .lt(Orders::getCreateTime, LocalDateTime.now().minusMinutes(15))//小于当前时间减去15分钟
                .last("limit " + 100)
                .list();
        if (CollUtil.isEmpty(orders)) {
            return;
        }

        //2、循环修改所有订单状态
        orders.forEach(o -> {
            OrderCancelDTO orderCancelDTO = BeanUtil.toBean(o, OrderCancelDTO.class);
            orderCancelDTO.setCurrentUserType(UserType.SYSTEM);
            orderCancelDTO.setCancelReason("超时未支付，自动取消！");
            ordersManagerService.cancel(orderCancelDTO);
        });
    }

    @XxlJob(value = "handleRefundOrders")
    public void handleRefundOrders() {
        //查询所有退款中的订单
        List<Orders> list = ordersManagerService.lambdaQuery()
                //查询已关闭的
                .eq(Orders::getOrdersStatus, OrderStatusEnum.CLOSED.getStatus())
                .eq(Orders::getRefundStatus, 1)
                .last("limit " + 100)
                .list();

        //查询所有取消订单
        list.forEach(e -> {
            log.error(e.toString());
            ordersHandler.extracted(new OrdersRefund(e.getId(), e.getTradingOrderNo(), e.getRealPayAmount(), e.getCreateTime()));
        });
    }

    @Transactional(rollbackFor = Exception.class)
    public void extracted(OrdersRefund ordersRefund) {
        //调用第三方退款
        ExecutionResultResDTO executionResultResDTO
                = refundRecordApi.refundTrading(ordersRefund.getTradingOrderNo(), ordersRefund.getRealPayAmount());
        //处理退款后内容
        if (executionResultResDTO != null) {
            //1. 从响应结果中确定退款状态
            if (executionResultResDTO.getRefundStatus() <= 1) {
                return;
            }

            //2. 更新订单表中的退款状态
            Orders orders = BeanUtil.copyProperties(executionResultResDTO, Orders.class);
            orders.setId(ordersRefund.getId());
            int result = ordersMapper.updateById(orders);
            //3. 删除待退款表中记录
            if (result > 0) {
                ordersRefundMapper.deleteById(ordersRefund.getId());
            }
        }
    }


}
